
// 设置全局变量
// var service_ip = "http://localhost:8080/";   
 var service_ip = "http://xxxx:8080/";  // 切换成自己的服务器地址
var token = "";
var jwt = "";
var settings;

jwt = window.localStorage.getItem("jwt")==null?getCookie("jwt"):window.localStorage.getItem("jwt");
if(jwt=="" || jwt ==null || jwt =="null"){
	initToken();
}


function setCookie(cname,cvalue,exdays)
{
  var d = new Date();
  d.setTime(d.getTime()+(exdays*24*60*60*1000));
  var expires = "expires="+d.toGMTString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname)
{
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) 
  {
    var c = ca[i].trim();
    if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
  return "";
}

function initToken(){
	 // 获取后台服务Token
	$.get(service_ip+"xl/common/getToken",function(data){
		token = data.data;
	   window.localStorage.setItem("token",token);
	   setCookie("token",token,1);
   }); 
   


     token = window.localStorage.getItem("token")==null?getCookie("token"):window.localStorage.getItem("token");
	 console.log(token);
	 
	  settings = {
			  "url": service_ip+"xl/demo/test/getToken",
			  "method": "GET",
			  "timeout": 0,
			  "headers": {
				"idempotent_token": token
			  }
			};
	$.ajax(settings).done(function (response) {
	  jwt = response.data;
	  // alert(jwt);
	  // 存储jwt令牌
	  window.localStorage.setItem("jwt",jwt);
	  jwt = setCookie("jwt",jwt,1);
	  // console.log(jwt);
	});
	
}
  
  
  function getJwt(){
	  jwt = window.localStorage.getItem("jwt")==null?getCookie("jwt"):window.localStorage.getItem("jwt");
  }


	
	function post(reqUrl){
		getJwt();
		var data = [];
		var settings = {
		"url": service_ip+reqUrl,
		"method": "POST",
		"async":false,
		"timeout": 0,
		"headers": {
		"X-Access-Token": jwt,
		"Content-Type": "application/json"
		},
		"data": JSON.stringify({}),
		};

		$.ajax(settings).done(function (response) {
		// console.log(response.data);
		 data = response;
		});
		return data;
	}
	
	function postForParams(reqUrl,params){
		getJwt();
		var data = [];
		var settings = {
		"url": service_ip+reqUrl,
		"method": "POST",
		"async":false,
		"timeout": 0,
		"headers": {
		"X-Access-Token": jwt,
		"Content-Type": "application/json"
		},
		"data": JSON.stringify(params),
		};

		$.ajax(settings).done(function (response) {
		// console.log(response.data);
		 data = response;
		});
		return data;
	}